package y2018.date0912.批量下载;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GenUrls {

    public static String[] getJiansheImgUrl(String url) {
        String[] resUrls = {};
        try {
            Document document = Jsoup.connect(url).get();
            Elements imgs = document.select(".artContent>p>img");
            resUrls = new String[imgs.size()];
            for (int i = 0; i < imgs.size(); i++) {
//				默认是相对路径。现在是绝对路径
                resUrls[i] = imgs.get(i).attr("abs:src");
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

        return resUrls;
    }

    public static String[] getAllImgUrlByRegex(String url) {
        ArrayList<String> resultUrls = new ArrayList<String>();
        try {
            Document document = Jsoup.connect(url).get();
            String html = document.toString();
//            System.out.println(html);

            Pattern p = Pattern.compile("(?<=[\" ])[^\" ]+?\\.(?:jpg|png|gif)");
            Matcher m = p.matcher(html);

            while (m.find()) {
                String matchUrl = m.group();
                Element el = document.createElement("img");
                el.attr("src", matchUrl);
                String absoluteImgUrl = el.attr("abs:src");
                resultUrls.add(absoluteImgUrl);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] result = resultUrls.toArray(new String[resultUrls.size()]);
        System.out.println(Arrays.toString(result));
        return result;

    }

}
